import React, {Component} from 'react';
import {connect} from "react-redux";
import {Spin, Switch, Form, Button, Radio, Icon, message} from "antd";
import {messages} from "share/common";
import Chooser from "components/chooser";
import Priority from "components/template/priority";
import WrapFormItem from "components/wrap-form-item";
import InputLanguage from "components/template/input-language";
import Condition from "components/condition";
import ExpenseAmount from "./expense-amount";
import ExpenseLabel from "./expense-label";
import CheckRatio from "./check-ratio";
import claimAmountService from "../../claim-amount.service";
import "styles/request-and-expense-settings/claim-amount-verification.scss";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { If } = Condition;

@Form.create()
@connect(mapStateToProps)
class ClaimAmountVerificationRuleDetail extends Component {

  state = {
    pageLoading: false,
    loading: false,
    info: {},
    enabled: true,
    priorityValue: {
      levelCode: 'TENANT',
      levelOrgId: this.props.params.record.levelOrgId || this.props.tenant.id,
      levelOrgName: this.props.params.record.levelOrgName || this.props.tenant.tenantName,
      distribution: {
        companies: this.props.params.record.companies
      }
    }
  };

  componentDidMount() {
    this.getDetail();
  }

  getDetail = () => {
    const { record } = this.props.params;
    if (record.id) {
      this.setState({ pageLoading: true });
      claimAmountService.getDiscountDetail(record.id)
        .then(res => {
          this.setState({
            pageLoading: false,
            info: this.filterInfo(res.data),
            enabled: res.data.enabled,
          })
        })
        .finally(() => {
          this.setState({ pageLoading: false });
        })
    }
  };

  filterInfo = info => {
    let { tieredProportions, discountProportion } = info;
    tieredProportions && tieredProportions.map(item => Object.assign(item, { hitValue: item.hitValue * 100 }));
    discountProportion && (discountProportion *= 100);
    info.tieredProportions = tieredProportions;
    info.discountProportion = discountProportion;
    return info;
  };

  /**
   * 检查费用金额限制是否符合要求
   * 1. 至少一侧有条件符
   * 2. 有条件符的一侧必须填写金额
   * 3. 有金额的一侧必须选择条件符
   * 4. 两侧都有条件符时，金额大小比较
   *    4.1. 若左侧条件符是< 或 右侧金额条件符是<，则左侧金额一定要小于右侧金额
   *    4.2. 非4.1的情况，则左侧金额小于等于右侧金额
   */
  checkAmountLimit = values => {
    let errorMsg = '';
    if (values.condExpAmount === "LIMIT") {
      const { startComparedSymbol, endComparedSymbol, startValue, endValue } = values.condExpAmountLimit;
      const startSymbol = startComparedSymbol === "NONE" ? undefined : startComparedSymbol,
        endSymbol = endComparedSymbol === "NONE" ? undefined : endComparedSymbol,
        hasStartValue = startValue || startValue === 0,
        hasEndValue = endValue || endValue === 0;
      if (
        (!startSymbol && !endSymbol) ||
        ((startSymbol && !hasStartValue) || (endSymbol && !hasEndValue)) ||
        ((hasStartValue && !startSymbol) || (hasEndValue && !endSymbol))
      ) {
        errorMsg = messages('expense-8.key410')/*费用金额表达式不合法*/;
      }
      if (startSymbol && endSymbol) {
        if (startSymbol === "LESS_THAN" || endSymbol === "LESS_THAN") {
          if (startValue >= endValue) {
            errorMsg = messages('expense-8.key410')/*费用金额表达式不合法*/;
          }
        } else {
          if (startValue > endValue) {
            errorMsg = messages('expense-8.key410')/*费用金额表达式不合法*/;
          }
        }
      }
    }
    return errorMsg;
  };

  /**
   * 检查核定比率设置是否符合要求
   * 1. 阶梯左边值不能为空
   * 2. 阶梯右边值只有最后一个可能为空（不限制）
   * 3. 同阶梯，右边值大于左边值
   * 4. 下一阶梯左边值等于上一阶梯右边值
   * 5. 扣减比率不能为空
   */
  checkDiscountProportion = values => {
    let errorMsg = '';
    const { tieredProportions, discountProportion } = values.discountInfo;
    if (values.discountMode === "TIERED_PROPORTION_BY_DAYS_OF_OVERDUE") {
      tieredProportions.map((item, index) => {
        if (
          !(+item.startValue || +item.startValue === 0) ||
          (index < tieredProportions.length - 1 && !item.endValue) ||
          (item.endValue && +item.endValue <= +item.startValue) ||
          (index > 0 && +item.startValue !== +tieredProportions[index - 1].endValue)
        ) {
          errorMsg = messages('expense-8.key411')/*请修改阶梯设置*/;
        }
        if (!item.hitValue) {
          errorMsg = messages('expense-8.key412')/*请填写扣减比率*/;
        }
      });
    } else if (!discountProportion) {
      errorMsg = messages('expense-8.key412')/*请填写扣减比率*/;
    }
    return errorMsg;
  };

  handleSave = () => {
    const { validateFieldsAndScroll } = this.props.form;
    const { info, priorityValue } = this.state;
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        const errorMsg = this.checkAmountLimit(values) || this.checkDiscountProportion(values);
        if (errorMsg) {
          message.error(errorMsg);
          return;
        }
        values.id = info.id;
        values.levelCode = priorityValue.levelCode;
        values.levelOrgId = priorityValue.levelOrgId;
        values.levelOrgName = priorityValue.levelOrgName;
        values.companies = (priorityValue.distribution && priorityValue.distribution.companies) || [];
        values.i18n = { ruleName: values.ruleName.i18n };
        values.ruleName = values.ruleName.name;
        if (values.ruleDesc) {
          values.i18n.ruleDesc = values.ruleDesc.i18n;
          values.ruleDesc = values.ruleDesc.name;
        }
        values.condFormTypeLimit && (values.condFormTypeLimit = values.condFormTypeLimit.map(item => {
          return { id: item.id, formName: item.formName };
        }))
        values.condExpTypeLimit && (values.condExpTypeLimit = values.condExpTypeLimit.map(item => {
          return { id: item.id, name: item.name };
        }))
        values.condExpLabels = values.condExpLabels.value;
        values.discountAmountBerk = "EXP_ORI_AMOUNT"; // 扣减⾦额基准
        values.discountCalcType = "DEDUCT_EXP_AMOUNT"; // 核定⽅式
        if (values.discountMode === "TIERED_PROPORTION_BY_DAYS_OF_OVERDUE") {
          values.tieredProportions = values.discountInfo.tieredProportions;
          values.tieredProportions.map(item => Object.assign(item, { hitValue: (item.hitValue / 100).toFixed(4) }));
          values.discountProportion = undefined;
          delete values.discountInfo;
        } else {
          values.discountProportion = (values.discountInfo.discountProportion / 100).toFixed(4);
          values.tieredProportions = undefined;
        }
        this.setState({ loading: true });
        claimAmountService.saveDiscountRule(values)
          .then(res => {
            this.setState({ loading: false });
            message.success(messages('expense-8.key21')/*保存成功*/);
            this.props.close(true);
          })
          .finally(() => {
            this.setState({ loading: false });
          })
      }
    })
  };

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { disabled } = this.props.params;
    const { pageLoading, loading, info, enabled, priorityValue } = this.state;
    const isLadderMode = getFieldValue('discountMode') === 'TIERED_PROPORTION_BY_DAYS_OF_OVERDUE';
    return (
      <div className="verification-rule-detail">
        <Spin spinning={pageLoading}>
          <Form className="new-form">
            <FormItem label={messages('common.column.status')/*状态*/}>
              {getFieldDecorator('enabled', {
                valuePropName: 'checked',
                initialValue: info.id ? info.enabled : true
              })(
                <Switch disabled={info.readOnly} onChange={enabled => this.setState({ enabled })}/>
              )}
              <span className="switch-desc">
              {enabled ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
            </span>
            </FormItem>
            <Priority
              disabled={info.readOnly}
              disabledTop
              companyProps={{ disabled: info.readOnly }}
              top="TENANT"
              formItemLayout={{}}
              defaultValue={priorityValue}
              required
              onChange={value => this.setState({ priorityValue: value })}
            />
            <FormItem label={messages('expense-8.key10')/*规则名称*/}>
              {getFieldDecorator("ruleName", {
                rules: [{
                  validator: (item, value, callback) => {
                    if (!(value && value.name)) {
                      callback(messages('common.please.input')/*请输入*/);
                    }
                    callback();
                  }
                }, {
                  required: true,
                  message: messages('common.please.input')/*请输入*/
                }],
                initialValue: info.ruleName ? { name: info.ruleName, i18n: info.i18n ? info.i18n.ruleName : [] } : undefined
              })(
                <InputLanguage
                  placeholder={messages('expense-8.key413')/*请输入规则名称，最大100字符*/}
                  maxLength={100}
                />
              )}
            </FormItem>
            <FormItem label={messages('expense-8.key116')/*提示内容*/}>
              {getFieldDecorator("ruleDesc", {
                initialValue: info.ruleDesc ? { name: info.ruleDesc, i18n: info.i18n ? info.i18n.ruleDesc : [] } : undefined
              })(
                <InputLanguage
                  placeholder={messages('expense-8.key414')/*请输入提示内容，最大300字符*/}
                  maxLength={300}
                  textArea
                />
              )}
            </FormItem>

            <div className="sub-title">{messages('expense-8.key415')/*规则条件*/}</div>
            <FormItem label={messages('expense-8.key416')/*表单类型*/}>
              {getFieldDecorator('condFormTypeLimit', {
                initialValue: info.condFormTypeLimit
              })(
                <Chooser
                  type="select_tenant_forms"
                  valueKey="formOID"
                  labelKey="formName"
                  disabled={info.readOnly}
                  placeholder={messages('expense-8.key9')/*通用*/}
                  listExtraParams={{ formTypeList: [3001, 3002, 3003] }}
                />
              )}
            </FormItem>
            <FormItem label={messages('common.expense.type')/*费用类型*/}>
              {getFieldDecorator('condExpTypeLimit', {
                initialValue: info.condExpTypeLimit
              })(
                <Chooser
                  type="selectInvoiceType"
                  valueKey="id"
                  labelKey="name"
                  disabled={info.readOnly}
                  placeholder={messages('expense-8.key9')/*通用*/}
                  listExtraParams={{ levelCode: "ALL" }}
                />
              )}
            </FormItem>
            <FormItem label={messages('expense-8.key45')/*费用金额*/}>
              {getFieldDecorator('condExpAmount', {
                initialValue: info.condExpAmount || "NO_LIMIT"
              })(
                <RadioGroup
                  disabled={info.readOnly}
                  options={[
                    {label: messages('expense-8.key417')/*限制*/, value: "LIMIT"},
                    {label: messages('expense-8.key75')/*不限制*/, value: "NO_LIMIT"}
                  ]}
                />
              )}
            </FormItem>
            {getFieldValue('condExpAmount') === "LIMIT" && (
              <FormItem label=" ">
                {getFieldDecorator('condExpAmountLimit', {
                  initialValue: info.condExpAmountLimit || {
                    compareValueCode: "EXP_ORI_AMOUNT",
                    startComparedSymbol: "LESS_THAN_OR_EQUALS",
                    endComparedSymbol: "LESS_THAN"
                  }
                })(
                  <WrapFormItem parser={value => value || {}}>
                    {(onChange, value) => (
                      <ExpenseAmount
                        disabled={info.readOnly}
                        value={value}
                        onChange={onChange}
                      />
                    )}
                  </WrapFormItem>
                )}
              </FormItem>
            )}
            <FormItem label={messages('expense-8.key418')/*费用标签*/}>
              {getFieldDecorator('condExpLabels', {
                initialValue: {
                  value: info.condExpLabels || [
                    { condExpLabel: "CONTAINS" },
                    { condExpLabel: "CONTAINS" }
                  ]
                }
              })(
                <WrapFormItem parser={value => value || {}}>
                  {(onChange, value) => {
                    value.value && value.value.map((item, index) => Object.assign(item, { id: index }));
                    return (
                      <ExpenseLabel
                        disabled={info.readOnly}
                        value={value.value || []}
                        onChange={onChange}
                      />
                    )
                  }}
                </WrapFormItem>
              )}
            </FormItem>

            <div className="sub-title">{messages('expense-8.key419')/*核定设置*/}</div>
            <FormItem
              label={messages('expense-8.key420')/*扣减⾦额基准*/}
              extra={messages('expense-8.key421')/*核定差额 = 费⽤原⾦额 * 核定⽐率*/}
            >
              {messages('expense-8.key422')/*费⽤原⾦额*/}
            </FormItem>
            <FormItem label={messages('expense-8.key423')/*核定⽐率*/}>
              {getFieldDecorator('discountMode', {
                initialValue: info.discountMode || "TIERED_PROPORTION_BY_DAYS_OF_OVERDUE"
              })(
                <RadioGroup
                  disabled={info.readOnly}
                  options={[
                    {label: messages('expense-8.key424')/*固定⽐率*/, value: "FIXED_PROPORTION"},
                    {label: messages('expense-8.key425')/*按逾期天数设置比率*/, value: "TIERED_PROPORTION_BY_DAYS_OF_OVERDUE"}
                  ]}
                />
              )}
            </FormItem>
            {isLadderMode && (
              <FormItem label=" " className="verification-rule-detail-days">
                <div className="verification-rule-detail-days-title">{messages('expense-8.key398')/*逾期天数*/}</div>
                {getFieldDecorator('overdueFormula', {
                  initialValue: info.overdueFormula || "FIRST_SUBMITED_DATE_SUBTRACT_BUSINESS_END_DATE"
                })(
                  <RadioGroup
                    style={{ width: '100%' }}
                    disabled={info.readOnly}
                  >
                    <Radio value="FIRST_SUBMITED_DATE_SUBTRACT_BUSINESS_END_DATE">
                      {messages('expense-8.key426')/*单据⾸次提交⽇期 - 消费结束⽇期*/} <br/>
                    </Radio>
                    <div className="verification-rule-detail-days-extra">
                      {messages('expense-8.key427')/*费⽤消费⽇期获取优先级：补贴明细⽇期中最晚的⽇期*/}
                      <Icon type="arrow-right" />
                      {messages('expense-8.key428')/*开始结束⽇期中结束⽇期*/}
                      <Icon type="arrow-right" />
                      {messages('expense-8.key429')/*费⽤发⽣⽇期*/}
                    </div>
                    <Radio value="FIRST_SUBMITED_DATE_SUBTRACT_RECEIPT_BILLING_DATE">
                      {messages('expense-8.key430')/*单据⾸次提交⽇期 - 发票开票⽇期*/}
                    </Radio>
                  </RadioGroup>
                )}
              </FormItem>
            )}
            <FormItem label=" ">
              {getFieldDecorator('discountInfo', {
                initialValue: {
                  discountProportion: info.discountProportion,
                  tieredProportions: info.tieredProportions || [{
                    startValue: 0,
                    compareValueCode: "DAYS_OF_OVERDUE",
                    startComparedSymbol: "LESS_THAN_OR_EQUALS",
                    endComparedSymbol: "LESS_THAN",
                    hitValueType: "NUMBER"
                  }]
                }
              })(
                <WrapFormItem parser={value => value || {}}>
                  {(onChange, value) => {
                    value.tieredProportions && value.tieredProportions.map((item, index) => Object.assign(item, { id: index }));
                    return (
                      <CheckRatio
                        disabled={info.readOnly}
                        isLadder={isLadderMode}
                        value={value}
                        onChange={onChange}
                      />
                    )
                  }}
                </WrapFormItem>
              )}

            </FormItem>
            <FormItem
              label={messages('expense-8.key431')/*核定⽅式*/}
              extra={messages('expense-8.key432')/*费⽤核定⾦额 = 费⽤原⾦额 - 核定差额*/}
            >
              {messages('expense-8.key433')/*扣减费⽤*/}
            </FormItem>
          </Form>
        </Spin>
        <div className="slide-footer">
          <If value={!disabled}>
            <Button type="primary" loading={loading} onClick={this.handleSave}>{messages('common.save')/*保存*/}</Button>
          </If>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant
  }
}


export default ClaimAmountVerificationRuleDetail;
